//
//  TabBar.swift
//  开心微博
//
//  Created by 郑开心 on 15/12/6.
//  Copyright © 2015年 郑开心. All rights reserved.
//

import UIKit

protocol TabBarDelegate {
    func tabBar(tabeBar: TabBar,didClickButton index: Int)
}

class TabBar: UITabBar {

    var myDelegate : TabBarDelegate?
    
    lazy var plusButton : UIButton! = {
        let btn = UIButton(type: UIButtonType.Custom)
        btn.setImage(UIImage(named: "tabbar_compose_icon_add"), forState: UIControlState.Normal)
        btn.setImage(UIImage(named: "tabbar_compose_background_icon_add"), forState: UIControlState.Highlighted)
        btn.setBackgroundImage(UIImage(named: "tabbar_compose_button"), forState: UIControlState.Normal)
        btn.setBackgroundImage(UIImage(named: "tabbar_compose_button_highlighted"), forState: UIControlState.Highlighted)
        btn.sizeToFit()
        self.addSubview(btn)
        return btn
    }()

    var selectedButton : UIButton?
    
    var kxitems : [UITabBarItem] = [UITabBarItem](){
        didSet{
            setItems()
        }
    }
    
    lazy var buttons : [UIButton] = {
        let buttons = [UIButton]()
        return buttons
    }()
    
    override func layoutSubviews() {
        super.layoutSubviews()
        let w = self.bounds.size.width
        let h = self.bounds.size.height
        
        var btnX : CGFloat = 0
        let btnY : CGFloat = 0
        let btnW : CGFloat = w / CGFloat(self.kxitems.count + 1)
        let btnH : CGFloat = h
        var i : CGFloat = 0
        for view in self.buttons {
            if i == 2 {
                i = 3
            }
            
            btnX = i * btnW
            view.frame = CGRectMake(btnX, btnY, btnW, btnH)
            i++
        }
        
        plusButton.center = CGPointMake(w * 0.5,h * 0.5)
//        plusButton.bounds = CGRectMake(0, 0, (plusButton.currentBackgroundImage?.size.width)!, (plusButton.currentBackgroundImage?.size.height)!)
    }
    
    func setItems(){
        for item in kxitems {
            let btn = TabBarButton(type: UIButtonType.Custom)
            btn.item = item
            btn.tag = self.buttons.count
            
            btn.addTarget(self, action: "btnClick:", forControlEvents: UIControlEvents.TouchDown)
            
            if btn.tag == 0 {
                selectedButton = btn
                self.btnClick(btn)
            }
            
            self.addSubview(btn)
            buttons.append(btn)
        }
    }
    
    func btnClick(button: UIButton){
        selectedButton!.selected = false
        button.selected = true
        selectedButton = button
        
        myDelegate?.tabBar(self, didClickButton: button.tag)
    }
}
